<template>
  <div class="component-upload-image">
    <el-upload
      multiple
      :auto-upload="false"
      :action="uploadImgUrl"
      list-type="picture-card"
      :on-success="handleUploadSuccess"
      :before-upload="handleBeforeUpload"
      :on-change="onChange"
      :limit="limit"
      :data="uploadData"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      ref="imageUpload"
      :before-remove="handleDelete"
      :show-file-list="true"
      :headers="headers"
      :file-list="fileList"
      :on-preview="handlePictureCardPreview"
      :class="{ hide: fileList.length >= limit }"
    >
      <el-icon class="avatar-uploader-icon">
        <plus />
      </el-icon>
    </el-upload>
    <!-- 上传提示 -->
    <div class="el-upload__tip" v-if="showTip">
      请上传
      <template v-if="fileSize">
        大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
      </template>
      <template v-if="fileType">
        格式为 <b style="color: #f56c6c">{{ fileType.join('/') }}</b>
      </template>
      的文件
    </div>

    <div class="el-upload__tip" v-if="limitShowTip">
      请上传
      <template v-if="fileSize">
        大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
      </template>
      <template v-if="fileType">
        格式为 <b style="color: #f56c6c">{{ fileType.join('/') }}</b>
      </template>
      的文件且宽高为
      <b v-if="limitatSize == 'banner'" style="color: #f56c6c">1920 * 360</b>
      <b v-else style="color: #f56c6c">648*432 或 864*576</b>
    </div>

    <div v-if="isShow">
      <p class="el-upload__tip">
        建议上传视频：比例16：9，分辨率：1280*720，视频大小不超过2G
      </p>
    </div>

    <div v-if="custom">
      <p class="el-upload__tip-1">
        建议尺寸比例为16:9，只能上传jpg/png文件，大小不超过2mb
      </p>
    </div>

    <el-dialog
      v-model="dialogVisible"
      title="预览"
      width="800px"
      append-to-body
    >
      <img
        :src="dialogImageUrl"
        style="display: block; max-width: 100%; margin: 0 auto"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { getToken } from '@/utils/auth';
import { upImg } from '@/api/upload.js';
import { ElMessage } from 'element-plus';
const props = defineProps({
  modelValue: {
    type: [String, Object, Array],
    default: [],
  },
  // 图片数量限制
  limit: {
    type: Number,
    default: 5,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 5,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => ['png', 'jpg', 'jpeg'],
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true,
  },
  // 获取token信息
  imageUpload: {
    type: Object,
    default: {},
  },
  isShow: {
    type: Boolean,
    default: false,
  },
  custom: {
    type: Boolean,
    default: false,
  },
  limitatSize: {
    type: String,
    default: '',
  },
  limitShowTip: {
    type: Boolean,
    default: false,
  },
});

const { proxy } = getCurrentInstance();
const emit = defineEmits(['update:modelValue']);
const number = ref(0);
const uploadList = ref([]);
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(
  import.meta.env.VITE_APP_BASE_API + '/api/index/imageUpload'
);
const headers = ref({ token: getToken() });
const fileList = ref([]);
// 额外的上传参数
const uploadData = ref({});
const showTip = computed(
  () => props.isShowTip && (props.fileType || props.fileSize)
);

watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      // 首先将值转为数组
      const list = Array.isArray(val) ? val : props.modelValue.split(',');
      // 然后将数组转为对象数组
      fileList.value = list.map((item) => {
        if (typeof item === 'string') {
          if (item.indexOf(baseUrl) === -1) {
            item = { name: baseUrl + item, url: item };
          } else {
            item = { name: item, url: item };
          }
        }
        return item;
      });
    } else {
      fileList.value = [];
      return [];
    }
  },
  { deep: true, immediate: true }
);

const url = ref('');
function onChange(res, file) {
  const image = new Image();
  const reader = new FileReader();

  // 处理图片上传
  const fileObject = file[0]?.raw || res.raw;

  // 确保是图片格式
  if (!fileObject.type.includes('image/')) {
    proxy.$modal.msgError(
      '文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。'
    );
    return;
  }

  // 使用 FileReader 读取文件并加载图片
  reader.onload = (e) => {
    image.src = e.target.result;
  };

  // 图片加载成功后获取图片的宽高并进行判断
  image.onload = () => {
    const width = image.width;
    const height = image.height;

    // 限制图片的宽高
    if (props.limitatSize) {
      if (props.limitatSize == 'banner' && width == 1920 && height == 360) {
        // ElMessage.error('图片宽高需要大于 500x500px');
        // 图片符合要求，继续执行上传操作
        processFileUpload(fileObject); // 调用处理上传的函数
        return; // 阻止上传
      } else if (
        (props.limitatSize === 'infoBanner' &&
          (width === 648 || width === 432)) ||
        height === 864 ||
        height === 576
      ) {
        processFileUpload(fileObject); // 调用处理上传的函数
        return;
      } else {
        proxy.$refs.imageUpload.clearFiles(); // 直接清除所有文件
        ElMessage.error('图片尺寸不匹配，请选择符合要求的尺寸');
        return;
      }
    }

    // // 图片符合要求，继续执行上传操作
    processFileUpload(fileObject); // 调用处理上传的函数
  };

  reader.readAsDataURL(fileObject); // 读取图片文件

  // 提取文件扩展名
  function processFileUpload(fileObject) {
    url.value = res.raw;
    let info = fileObject || {};
    let fileExtension = '';
    if (info.name.lastIndexOf('.') > -1) {
      fileExtension = info.name.slice(info.name.lastIndexOf('.') + 1);
    }

    // 准备上传的数据
    uploadData.value['type'] = fileExtension;
    uploadData.value['image'] = fileObject;

    // 调用上传接口
    upImg(uploadData.value).then((res) => {
      if (res.code === 20000) {
        number.value++;
        uploadList.value.push({ url: `${res.data.url}` });
        uploadedSuccessfully();
      } else {
        proxy.$modal.closeLoading();
        proxy.$modal.msgError(res.msg);
        proxy.$refs.imageUpload.handleRemove(fileObject);
        uploadedSuccessfully();
      }
    });
  }
}

// function onChange(res, file) {
//   console.log('props.modelValue:', props.type);
//   if (!res.raw.type.includes('image/')) {
//     proxy.$modal.msgError(
//       '文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。'
//     );
//   } else {
//     url.value = res.raw;

//     let info = file[0] || {};
//     let fileExtension = '';
//     if (info.name.lastIndexOf('.') > -1) {
//       fileExtension = info.name.slice(info.name.lastIndexOf('.') + 1);
//     }

//     uploadData.value['type'] = fileExtension;

//     uploadData.value['image'] = file[0].raw;
//     upImg(uploadData.value).then((res) => {
//       if (res.code == 20000) {
//         number.value++;
//         uploadList.value.push({ url: `${res.data.url}` });
//         uploadedSuccessfully();
//       } else {
//         proxy.$modal.closeLoading();
//         proxy.$modal.msgError(res.msg);

//         proxy.$refs.imageUpload.handleRemove(file);
//         uploadedSuccessfully();
//       }
//     });
//   }
// }

// 上传前loading加载
function handleBeforeUpload(file) {
  let isImg = false;
  if (props.fileType.length) {
    let fileExtension = '';
    if (file.name.lastIndexOf('.') > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1);
    }
    isImg = props.fileType.some((type) => {
      if (file.type.indexOf(type) > -1) return true;
      if (fileExtension && fileExtension.indexOf(type) > -1) return true;
      return false;
    });

    uploadData.value['type'] = fileExtension;
    uploadData.value['image'] = url.value;
  } else {
    isImg = file.type.indexOf('image') > -1;
  }
  if (!isImg) {
    proxy.$modal.msgError(
      `文件格式不正确, 请上传${props.fileType.join('/')}图片格式文件!`
    );
    return false;
  }
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      proxy.$modal.msgError(`上传头像图片大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  proxy.$modal.loading('正在上传图片，请稍候...');
  number.value++;
}

// 文件个数超出
function handleExceed() {
  proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
}

// 上传成功回调
function handleUploadSuccess(res, file) {
  if (res.key) {
    uploadList.value.push({ url: `http://mcdn.chatgk.com/${res.key}` });
    uploadedSuccessfully();
  } else {
    number.value--;
    proxy.$modal.closeLoading();
    proxy.$modal.msgError(res.msg);

    proxy.$refs.imageUpload.handleRemove(file);
    uploadedSuccessfully();
  }
}

// 删除图片
function handleDelete(file) {
  const findex = fileList.value.map((f) => f.name).indexOf(file.name);
  if (findex > -1 && uploadList.value.length === number.value) {
    fileList.value.splice(findex, 1);
    emit('update:modelValue', listToString(fileList.value));
    return false;
  }
}

// 上传结束处理
function uploadedSuccessfully() {
  if (number.value > 0 && uploadList.value.length === number.value) {
    fileList.value = fileList.value
      .filter((f) => f.url !== undefined)
      .concat(uploadList.value);

    uploadList.value = [];
    number.value = 0;
    emit('update:modelValue', listToString(fileList.value));
  }
}

// 上传失败
function handleUploadError() {
  proxy.$modal.msgError('上传图片失败');
  proxy.$modal.closeLoading();
}

// 预览
function handlePictureCardPreview(file) {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
}

// 对象转成指定字符串分隔
function listToString(list, separator) {
  let strs = '';
  separator = separator || ',';
  for (let i in list) {
    if (undefined !== list[i].url && list[i].url.indexOf('blob:') !== 0) {
      strs += list[i].url.replace(baseUrl, '') + separator;
    }
  }
  return strs != '' ? strs.substr(0, strs.length - 1) : '';
}
</script>

<style scoped lang="scss">
// .el-upload--picture-card 控制加号部分
:deep(.hide .el-upload--picture-card) {
  display: none;
}
.el-upload__tip {
  font-size: 12px;
  color: #4e5969;
  margin-top: 7px;
}
.el-upload__tip-1 {
  font-size: 12px;
  color: #4e5969;
  margin-top: 7px;
}
</style>
